package xyf.p07.binsearch;

/**
 * ClassName: P0074_SearchMatrix
 * Description:
 * Author: xyf
 * Date: 9/7/22 7:03 PM
 * Version: 1.0
 **/
public class P0074_SearchMatrix
{
    public boolean searchMatrix(int[][] matrix, int target)
    {
        //找第一个大于目标值的行
        int start = 0;
        int end = matrix.length - 1;
        int col = matrix[0].length - 1;
        int targetRow = -1;
        while (start <= end)
        {
            int middle = (end - start) / 2 + start;

            if (matrix[middle][col] == target)
            {
                return true;
            }
            else if (matrix[middle][col] < target)
            {
                start = middle + 1;
            }
            else
            {
                end = middle - 1;
            }
        }
        targetRow = start;
        if (targetRow >= matrix.length)
        {
            return false;
        }

        start = 0;
        end = matrix[0].length - 1;
        while (start <= end)
        {
            int middle = (end - start) / 2 + start;

            if (matrix[targetRow][middle] == target)
            {
                return true;
            }
            else if (matrix[targetRow][middle] < target)
            {
                start = middle + 1;
            }
            else
            {
                end = middle - 1;
            }
        }

        return false;
    }
}